package com.yf.course.modules.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.ability.redis.service.RedisService;
import com.yf.ability.upload.service.UploadService;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.base.utils.BeanMapper;
import com.yf.course.modules.course.dto.CourseFaceCaptureDTO;
import com.yf.course.modules.course.dto.request.CourseFaceCaptureReqDTO;
import com.yf.course.modules.course.dto.response.CaptureRespDTO;
import com.yf.course.modules.course.entity.Course;
import com.yf.course.modules.course.entity.CourseFaceCapture;
import com.yf.course.modules.course.mapper.CourseFaceCaptureMapper;
import com.yf.course.modules.course.service.CourseFaceCaptureService;
import com.yf.course.modules.course.service.CourseService;
import com.yf.system.modules.user.UserUtils;
import com.yf.system.modules.user.dto.response.FaceCheckRespDTO;
import com.yf.system.modules.user.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Date;

/**
* <p>
* 学习截屏记录业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2022-04-25 10:35
*/
@Service
public class CourseFaceCaptureServiceImpl extends ServiceImpl<CourseFaceCaptureMapper, CourseFaceCapture> implements CourseFaceCaptureService {

    @Autowired
    private CourseService courseService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private RedisService redisService;

    @Override
    public IPage<CourseFaceCaptureDTO> paging(PagingReqDTO<CourseFaceCaptureDTO> reqDTO) {

        //查询条件
        QueryWrapper<CourseFaceCapture> wrapper = new QueryWrapper<>();

        // 请求参数
        CourseFaceCaptureDTO params = reqDTO.getParams();

        if(params!=null){
            if(StringUtils.isNoneBlank(params.getCourseId())){
                wrapper.lambda().eq(CourseFaceCapture::getCourseId, params.getCourseId());
            }
            if(StringUtils.isNoneBlank(params.getUserId())){
                wrapper.lambda().eq(CourseFaceCapture::getUserId, params.getUserId());
            }
            if(StringUtils.isNoneBlank(params.getFileId())){
                wrapper.lambda().eq(CourseFaceCapture::getFileId, params.getFileId());
            }
        }

        wrapper.lambda().orderByDesc(CourseFaceCapture::getCreateTime);

        //获得数据
        IPage<CourseFaceCapture> page = this.page(reqDTO.toPage(), wrapper);
        //转换结果
        IPage<CourseFaceCaptureDTO> pageData = JSON.parseObject(JSON.toJSONString(page), new TypeReference<Page<CourseFaceCaptureDTO>>(){});
        return pageData;
    }


    @Override
    public CaptureRespDTO save(CourseFaceCaptureReqDTO reqDTO){


        CourseFaceCapture entity = new CourseFaceCapture();
        BeanMapper.copy(reqDTO, entity);
        entity.setUserId(UserUtils.getUserId());
        entity.setCreateTime(new Date());

        Course course = courseService.getById(reqDTO.getCourseId());

        // 响应类
        CaptureRespDTO respDTO = new CaptureRespDTO();
        // 无限制响应
        respDTO.setFaceChance(0);
        respDTO.setIsBreak(false);
        respDTO.setFailCount(0);

        // 无需人脸识别
        if(course.getFaceCheck()==null
                || !course.getFaceCheck()
                || course.getFaceChance()==null
                || course.getFaceChance()== 0){
            // base64转URL
            String faceImage = uploadService.uploadBase64(reqDTO.getBase64(), IdWorker.getIdStr() + ".jpg");
            entity.setImage(faceImage);
            // 保存截屏
            this.save(entity);
            return respDTO;
        }

        // 总机会数
        respDTO.setFaceChance(course.getFaceChance());
        respDTO.setIsBreak(false);

        // 进行人脸识别
        FaceCheckRespDTO faceDTO = sysUserService.faceCheck(reqDTO.getBase64(), false);
        // 成功失败都保存
        entity.setImage(faceDTO.getFaceImage());

        // 识别通过删除错误记录
        String key = MessageFormat.format("yf:course-face-check:{1}-{2}", UserUtils.getUserId(), reqDTO.getFileId());
        if(faceDTO.isPass()){
            redisService.del(key);
            respDTO.setFailCount(0);
        }else{
            JSONObject json = redisService.getJson(key);
            int count = 1;
            if(json == null){
                json = new JSONObject();
            }else {
                count = json.getInteger("count");
                count += 1;
            }

            if(count >= course.getFaceChance()){
                respDTO.setIsBreak(true);
                // 置空
                count = 0;
            }

            // 设置值
            json.put("count", count);
            redisService.set(key, json.toJSONString(), 60 * 60 * 24L);
            // 返回响应
            respDTO.setFailCount(count);
        }

        // 先保存截屏
        this.save(entity);
        return respDTO;

    }
}
